package com.ruoyi.web.controller.market;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.market.domain.*;
import com.ruoyi.market.service.*;
import com.ruoyi.system.domain.SysCity;
import com.ruoyi.system.domain.SysProvince;
import com.ruoyi.system.service.SysCityService;
import com.ruoyi.system.service.SysProvinceService;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 订单管理控制器
 */
@Controller
@RequestMapping("/market/check")
public class CheckManagementController extends BaseController {

    private String prefix="market/check";

    @Autowired
    private RepoCkService2 repoCkService2;

    @Autowired
    private RepoWareService2 repoWareService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RepoKcService2 repoKcService2;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private PoProductService2 productService;

    @Autowired
    private SysProvinceService provinceService;

    @Autowired
    private SysCityService cityService;
    @RequiresPermissions("market:check:view")
    @GetMapping()
    public String customer(ModelMap mmap){
        SysUser user = getSysUser();
        mmap.put("user",user);
        return prefix + "/check";
    }

    /**
     * 查询客户管理信息列表
     */
    @RequiresPermissions("market:check:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Order order, ModelMap mmap)
    {
        //获取当前用户
        SysUser user = getSysUser();
        Integer userid=user.getUserId().intValue();
        order.setSysChkUserId(userid);
        mmap.put("user",user);
        startPage();
        //查询审核人是当前用户的订单
        List<Order> list = orderService.queryList(order);
        return getDataTable(list);
    }



    /**
     * 导出客户管理信息列表
     */
    @RequiresPermissions("market:check:export")
    @Log(title = "客户管理信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Order order)
    {
        List<Order> list = orderService.queryList(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        return util.exportExcel(list, "check");
    }

    /**
     * 客户管理信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        SysUser user = getSysUser();
        mmap.put("user",user);
        return prefix + "/add";
    }

    /**
     * 新增保存客户管理信息
     */
    @RequiresPermissions("market:check:add")
    @Log(title = "客户管理信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Order order)
    {
        return toAjax(orderService.save(order));
    }

    /**
     * 修改客户管理信息
     */
    @GetMapping("/assign/{id}")
    public String assign(@PathVariable("id") Integer id,ModelMap mmap)
    {
        Order order = orderService.getById(id);
        System.out.println(order);
        mmap.put("order", order);
        SysUser user = getSysUser();
        mmap.put("user",user);
        return prefix + "/assign";
    }



    /**
     * 客户浏览详情信息
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id,ModelMap mmap)
    {
        Order order = orderService.getById(id);
        System.out.println(order);
        mmap.put("order", order);

        SysUser user = getSysUser();
        mmap.put("user",user);
        return prefix + "/detail";
    }


    /**
     * 修改保存客户管理信息
     */
    @RequiresPermissions("market:check:assign")
    @Log(title = "客户管理信息", businessType = BusinessType.UPDATE)
    @PostMapping("/assign")
    @ResponseBody
    public AjaxResult assignSave(Order order)
    {
        return toAjax(orderService.updateById(order));
    }



    /**
     * 修改订单信息
     */
    @GetMapping("/edit/{orderIndent}")
    public String edit(@PathVariable("orderIndent") String orderIndent,ModelMap mmap) throws JsonProcessingException {
        //创建一个封装数据的对象
        Order2 order2=new Order2();
        System.out.println(orderIndent);
        //根据订单号查询订购单
        Order order = orderService.getByOrderIndent(orderIndent);
        //注入order数据
        order2.setCustomerName(customerService.findById(order.getMkCustomerId()).getName());
        order2.setOrderIndent(order.getOrderIndent());
        order2.setOrderTime(order.getOrderTime());
        order2.setSysOperUser(order.getSysOperUser());
        order2.setChkStatus(order.getChkStatus());
        order2.setOrderMoney(order.getOrderMoney());
        System.out.println(order);
        //根据订单号查询订购详情列表
        List<OrderDetail> detailList=orderDetailService.getDetailListBymkOrderIndent(orderIndent);
        //获取到商品详情列表
        List<PoProduct1> poProductList=new ArrayList<PoProduct1>();
        for (OrderDetail orderDetail : detailList) {
            System.out.println("数量"+orderDetail.getNum());
            PoProduct1 poProduct = productService.getById(orderDetail.getPoProductId());
            System.out.println(poProduct);
            poProductList.add(poProduct);
        }

        //把商品信息封装到PoProduct2集合中
        List<PoProduct2> poProduct2List=new ArrayList<PoProduct2>();

        Integer size=detailList.size();
        for (Integer i = 0; i < size; i++) {
            PoProduct2 poProduct2=new PoProduct2();
            poProduct2.setDetailId(detailList.get(i).getDetailId());
            poProduct2.setNum(detailList.get(i).getNum());
            poProduct2.setPrice(detailList.get(i).getPrice());
            poProduct2.setTotal(detailList.get(i).getTotal());

            poProduct2.setPoBrandId(poProductList.get(i).getPoBrandId());
            poProduct2.setPoTypeId(poProductList.get(i).getPoTypeId());
            poProduct2.setProductModel(poProductList.get(i).getProductModel());
            poProduct2.setUnit(poProductList.get(i).getUnit());

            poProduct2List.add(poProduct2);

            System.out.println("----3-----"+poProduct2);
        }

        mmap.put("poProductList", poProductList);
        mmap.put("detailList", detailList);

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(poProduct2List);
        mmap.addAttribute("poProduct2List", jsonStr);
        mmap.put("order2", order2);
        SysUser user = getSysUser();
        mmap.put("user",user);
        return prefix + "/edit";
    }






    /**
     * 修改保存客户管理信息
     */
    @RequiresPermissions("market:check:edit")
    @Log(title = "审核", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Order2 order2)
    {
        System.out.println("审核"+order2);
        Order order=new Order();
        //订单号
        order.setOrderIndent(order2.getOrderIndent());
        //意见
        order.setOpinion(order2.getOpinion());
        //审核时间
        order.setCheckTime(new Date());
        //审核状态
        order.setChkStatus(order2.getChkStatus());

//        order.setOrderTime(order2.getOrderTime());
//        order.setSysOperUser(order2.getSysOperUser());
//        order.setOrderMoney(order2.getOrderMoney());
//        //获取客户id注入order对象
//        order.setMkCustomerId(customerService.findByName(order2.getCustomerName()).getId());
        System.out.println(order);
        //审核订购单
        boolean flag1=orderService.modify(order);
        //如果审核状态通过且订购单修改成功则添加出库单
       if("2".equals(order2.getChkStatus())&&flag1==true){
           //再根据订单号查询订单
           Order order1 = orderService.getByOrderIndent(order.getOrderIndent());
           RepoCk2 repoCk2=new RepoCk2();
           repoCk2.setMkOrderIndent(order1.getOrderIndent());
           repoCk2.setRepoWareId(order1.getRepoWareId());
           repoCk2.setStatus("1");
           boolean save = repoCkService2.save(repoCk2);
           System.out.println("新增出库表："+save);
       }
        return toAjax(flag1);
        }

    /**
     * 删除客户管理信息
     */
    @RequiresPermissions("market:check:remove")
    @Log(title = "客户管理信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(orderService.removeByIds(Arrays.asList(ids)));
    }
}
